import 'dart:async';

import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/entity/count_entity.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/modle/login/entity/user_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/utils/log_util.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/shared_preferences_util.dart';
import 'dart:convert' as convert;

class BindPhoneBloc implements BlocBase {
  String _codeCountdownStr = '获取验证码';
  Color _colorStr = Colours.themeColor;
  int _countdownNum = 59;
  CountEntity _countEntity = CountEntity();
  Timer _countdownTimer;

  // Stream来处理计数器
  StreamController<Object> _counterController = StreamController<Object>();
  StreamSink<Object> get _countAdd => _counterController.sink;
  Stream<Object> get pushDate => _counterController.stream;

  //处理验证码启动线程
  StreamController<Object> _actionCodeController = StreamController<Object>();
  StreamSink get verificationDate => _actionCodeController.sink;

  StreamController<Object> _bindActionController = StreamController<Object>();
  //初始化动作
  StreamSink get bindDate => _bindActionController.sink;
  BindPhoneBloc() {
    _actionCodeController.stream.listen(startVerificationCodeTask);
    _bindActionController.stream.listen(bindData);
  }

  void startVerificationCodeTask(data) {
    if (data is String) {
      if ('获取验证码' != _codeCountdownStr) {
        return;
      }
      reGetCountdown();
      _genValidateCode4CustRegistTask(data);
    }
  }

  void bindData(data) {
    if (data is Map<String, dynamic>) {
      _bindTask(data);
    }
  }

  void _bindTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        BotToast.showLoading();
        HttpUtilAll.post(Apis.BIND_PHONE_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            SharedPreferencesUtil.addShare('password', data['pwd']);
            _loginUser(result);
            BotToast.showText(text: '绑定成功');
            RouteUtil.closeView();
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _loginUser(result) {
    UserEntity userEntity = UserEntity.fromJson(result);
    LogUtil.e(userEntity.toJson(), tag: 'UserEntity ...........');
    SharedPreferencesUtil.addShare(
        'userEntity', convert.jsonEncode(userEntity.toJson()));
    BaseConstant.name = userEntity.name;
    BaseConstant.nickname = userEntity.nickname;
    BaseConstant.phone = userEntity.phone;
    BaseConstant.capitalAccount = userEntity.capitalAccount;
    BaseConstant.integralAccount = userEntity.integralAccount;
    BaseConstant.allAccount = userEntity.allAccount;
    BaseConstant.dsAllAcct = userEntity.dsAllAcct;
    BaseConstant.idCard = userEntity.idCard;
    BaseConstant.code = userEntity.code;
    BaseConstant.reBuyQuanAcct = userEntity.reBuyQuanAcct;
    BaseConstant.token = userEntity.token;
    SharedPreferencesUtil.addShare('userName', userEntity.code);
    SharedPreferencesUtil.addShare('nickname', userEntity.nickname);
    SharedPreferencesUtil.addShare('userId', userEntity.userId);
    BaseConstant.weixinOperId = userEntity.weixinOperId;
    // js.context.callMethod('flutterAlert', [BaseConstant.weixinOperId]);
    BaseConstant.userId = userEntity.userId;
    BaseConstant.isRealNameAuthen = 'Y' == userEntity.realNameState;
    BaseConstant.isLogin = true;
    eventBus.fire(BlackEvent());
    eventBus.fire(BlackPageEvent());
    eventBus.fire(BlackForumEvent());
    eventBus.fire(BlackMoreEvent());
    eventBus.fire(ResetMoneyEvent());
  }

  void reGetCountdown() {
    // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
    // _codeCountdownStr = '已发送（${_countdownNum--}s）';
    _colorStr = Colours.gray_cc;
    _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
      if (_countdownNum > 0) {
        _codeCountdownStr = '已发送（${_countdownNum--}s）';
        _colorStr = Colours.gray_cc;
        _countEntity..isShowLoning = false;
      } else {
        _colorStr = Colours.themeColor;
        _codeCountdownStr = '获取验证码';
        _countdownNum = 59;
        cancelTimer();
        _countEntity..isShowLoning = true;
      }
      _countEntity
        ..codeCountdownStr = _codeCountdownStr
        ..colorStr = _colorStr;
      _countAdd.add(_countEntity);
    });
  }

  void cancelTimer() {
    if (_countdownTimer != null) {
      _countdownTimer.cancel();
      _countdownTimer = null;
    }
  }

  //注册时获取验证码
  void _genValidateCode4CustRegistTask(phone) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        Map<String, dynamic> data = Map();
        data['val'] = phone;
        BotToast.showLoading();
        HttpUtilAll.post(Apis.BINDPHONE_CODE_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            SvEntity svEntity = SvEntity.fromJson(result);
            LogUtil.e(svEntity.toJson(), tag: 'REGISTER_URL............');
            BotToast.showText(text: '短信验证码获取成功');
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _actionCodeController?.close();
    _counterController?.close();
    _bindActionController?.close();
    cancelTimer();
  }
}
